package com.hzhc.service.impl;

import com.hzhc.netty.NettyConfig;
import com.hzhc.service.PushService;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.AttributeKey;
import org.springframework.stereotype.Service;

import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName: PushServiceImpl
 * @Description:
 * @version 1.0
 * @author: duanhm
 * @Date: 2021/04/28 14:11:41
 *
 */
@Service
public class PushServiceImpl implements PushService {

    @Override
    public void pushMsgToOne(String devId, String msg) {
        ConcurrentHashMap<String, Channel> userChannelMap = NettyConfig.getUserChannelMap();
        Channel channel = userChannelMap.get(devId);
        if (channel != null) {
            channel.writeAndFlush(new TextWebSocketFrame(msg));
        }
    }

    @Override
    public void pushMsgToAll(String msg) {
        NettyConfig.getChannelGroup().writeAndFlush(new TextWebSocketFrame(msg));
    }


    @Override
    public boolean logoutWebSocket(String devId) {
        // ConcurrentHashMap<String, Channel> userChannelMap =
        // NettyConfig.getUserChannelMap();
        // ConcurrentHashMap<String, Channel> map = NettyConfig.getUserChannelMap();
        NettyConfig.getUserChannelMap().remove(devId);
        return false;
    }


    @Override
    public boolean userIsLogin(String userId) {
        ConcurrentHashMap<String, Channel> map = NettyConfig.getUserChannelMap();
        for (Entry<String, Channel> entry : map.entrySet()) {
            Channel chel = map.get(entry.getKey());
            AttributeKey<String> idkey = AttributeKey.valueOf(NettyConfig.USERID);
            String loginUserId = chel.attr(idkey).get();
            if(userId.equals(loginUserId)){
                return true;
            }
        }
        return false;
    }


}